/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="task-log">
        <sf-scrollbar ref="scrollBar" style="height: 95%" @resize="resize">
            <pre ref="logs">{{ logs }}</pre>
        </sf-scrollbar>
        <span class="sim-link" style="float: right" @click="openLogs">查看全量日志</span>
    </div>
</template>

<script>
import {isUndefined} from "src/util/typeof";

const JOB_LOG = '/task-manage/api/v1/jobs/logs'
export default {
    name: "Log",
    props: {
        data: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            timer: null,
            logs: '',
            params: {
                retryNo: 0,
                tail: 100,
            },
            ajax: null,
        }
    },
    computed: {
        id() {
            return this.data.id;
        }
    },
    async mounted() {
        if (isUndefined(this.id)) { // 只有页面初始化加载的时候才会这样，会自动关闭 不影响
            return;
        }
        this.$mask();
        await this.getLogs();
        this.$unmask();
    },
    methods: {
        resize() {
            this.$refs.scrollBar.vScroll(this.$refs.logs.scrollHeight);
        },
        openLogs() {
           window.open(`${JOB_LOG}/${this.id}?retryNo=0&tail=-1`,'_blank')
        },
        async getLogs() {
            const vm = this
            let jsonData = await this.$ajax.get(`${JOB_LOG}/${this.id}`, this.params,
                {
                    before(request) {
                        vm.ajax = request;
                    }
                });
            if (isUndefined(jsonData)) {
                return;
            }
            if (!jsonData.success) {
                if (this.logs !== '') {
                    this.$warn(jsonData?.msg || ('后续日志加载失败'), {autoHide: true})
                    return;
                }
                this.$emit('close-logs')
                this.$warn(_(jsonData?.msg || '获取日志失败'), {autoHide: true})
                return;
            }
            this.logs = jsonData.data.log;
            if (!jsonData.data.loopFlag) {
                this.$ok(_('日志加载完毕'));
                return;
            }
            this.timer = setTimeout(() => {
                this.getLogs();
            }, 1000)
            
        },
    },
    beforeDestroy() {
        this.logs = '';
        clearTimeout(this.timer)
        this.timer = null;
        if (this.ajax) {
            this.ajax.abort();
        }
    }
}
</script>

<style scoped lang="less">
.task-log {
    width: calc(100% - 36px);
    height: calc(100% - 9px);
    margin: 9px 18px 0 18px;
    
    pre {
        min-height: 750px;
        white-space: pre-wrap;
        background-color: #1E1E1E;
        color: #fff;
    }
}
</style>
